#include "datacollect_ecg.h"
#include "ui_datacollect_ecg.h"

#include <SeriaPortWork/serialworker.h>

DataCollect_ECG::DataCollect_ECG(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DataCollect_ECG)
{
    ui->setupUi(this);
    // 创建一个 QCustomPlot 对象
    customPlot = ui->widget_ecg;
    setupPlot();

}

DataCollect_ECG::~DataCollect_ECG()
{
    // worker->requestStop();
    // m_serialThread->quit();
    // m_serialThread->wait();
    delete worker;
    delete ui;
}

void DataCollect_ECG::startthread()
{
    setupSerialThread();
}
void DataCollect_ECG::setupPlot() {
    customPlot->addGraph();
    customPlot->xAxis->setLabel("时间 (秒)");
    customPlot->yAxis->setLabel("电压值");
    customPlot->xAxis->setRange(0, 8);
    customPlot->yAxis->setRange(-0.2, 0.2);
}


void DataCollect_ECG::setupSerialThread() {
    // m_serialThread = new QThread();
    worker = new SerialWorker();
    // worker->moveToThread(m_serialThread);

    // connect(m_serialThread, &QThread::started, worker, &SerialWorker::process);
    connect(worker, &SerialWorker::newECGWaveData, this, &DataCollect_ECG::handleECGData);
    // connect(worker, &SerialWorker::finished, m_serialThread, &QThread::quit);
    connect(worker, &SerialWorker::newEEGWaveData, this, &DataCollect_ECG::handleEEGData);
    // worker->MultiUSBDongleAPI_Init();
    // if(worker->OpenSerialPort()){
    //     qDebug()<<"setupSerialThread::"<<"OpenSerialPort success";
    //     worker->EEGStartOrder();
    //     // m_serialThread->start();
    // }
}

void DataCollect_ECG::handleECGData(QVector<double> ecgdata,QVector<double> respdata) {
    const double SAMPLE_INTERVAL = 0.004; // 250Hz = 4ms
    // 添加新数据
    for (double value : ecgdata) {
        if (m_yData.size()  >= 2000) {
            m_yData.removeFirst();
            m_xData.removeFirst();
        }
        m_yData.append(value);
        m_xData.append(m_currentTime);
        m_currentTime += SAMPLE_INTERVAL;
    }

    // 更新X轴范围
    double windowEnd = qMax(m_currentTime, 8.0);
    customPlot->xAxis->setRange(windowEnd - 8, windowEnd);
}
void DataCollect_ECG::handleEEGData(QVector<double> leftEEGdata,QVector<double> rightEEGdata,QVector<double> irdata,QVector<double> reddata) {
    const double SAMPLE_INTERVAL = 0.004; // 250Hz = 4ms
    // 添加新数据
    for (double value : leftEEGdata) {
        if (m_yData.size()  >= 2000) {
            m_yData.removeFirst();
            m_xData.removeFirst();
        }
        m_yData.append(value);
        m_xData.append(m_currentTime);
        m_currentTime += SAMPLE_INTERVAL;
    }

    // 更新X轴范围
    double windowEnd = qMax(m_currentTime, 8.0);
    customPlot->xAxis->setRange(windowEnd - 8, windowEnd);
    customPlot->graph(0)->setData(m_xData, m_yData);
    customPlot->replot();
}
